<template>
	<van-popup v-model:show="state.isShow" class="w-full" style="height: 100%" position="right">
		<div class="w-[0] absolute left-[-10px]">
			<ActionSelect ref="actionSelect" v-model:val="ActionVal" title="上分类型" :columns="Actions" @update="() => {
				if (actionChangeIndex == 1) {
					form.DepositType = ActionVal;
				}
				else
					form.WithdrawType= ActionVal;
			}" />
		</div>
		<div class="page">
			<global-header :title="title" @back="state.isShow = false" />
			<main class="page-main ">
				<van-field label="头像" readonly>
					<template #input>
						<van-uploader ref="uploaderRef" :max-count="1" @click="uploaderRef.chooseFile()" :preview-full-image="false"
							:model-value="[{ url: `${baseImgUrl}${form.Avatar.startsWith('/') ? '' : '/'}${form.Avatar}` }]"
							:after-read="(e) => {
								afterRead(e, form, 'Avatar')
							}" :deletable="false"></van-uploader>
					</template>
				</van-field>

				<van-field label="机器人名称" :border="false" v-model="form.Name" disabled readonly>
					<template #button v-if="!isEdit">
						<van-button size="small" icon="replay" type="default" class="icon" @click="handleRobotName"></van-button>
					</template>
				</van-field>
				<van-field label="机器人昵称" :border="false" v-model="form.Nickname" >
					<template #button v-if="!isEdit">
						<van-button size="small" icon="replay" type="default" class="icon" @click="handleRobotNickname"></van-button>
					</template>
				</van-field>
				<van-field label="状态" :border="false">
					<template #input>
						<div class="flex-1 flex ">
							<van-switch v-model="form.Status" :active-value="1" :inactive-value="0" active-color="#3976CC"
								inactive-color="#888" />
						</div>
					</template>
				</van-field>

				<van-field label="自动上分1" :model-value="Actions.find(m => m.value == form.DepositType)?.text" is-link readonly
					@click="() => {
						actionChangeIndex = 1;
						ActionVal = form.DepositType;
						actionSelect.handleShow()
					}"></van-field>
				<van-field label="上分金额" :border="false" v-model="form.DepositAmount" placeholder="200#300#500#800#1000" />


				<van-field label="自动上分2" :model-value="Actions.find(m => m.value == form.WithdrawType)?.text" is-link readonly
					@click="() => {
						actionChangeIndex = 2;
						ActionVal = form.WithdrawType;
						actionSelect.handleShow()
					}"></van-field>
				<van-field label="上分金额" :border="false" v-model="form.WithdrawAmount" placeholder="200#300#500#800#1000" />
				<van-field label="最小下注金额" :border="false" v-model="form.MiniBet" type="digit" />
				<van-field label="最大下注金额" :border="false" v-model="form.MaxBet" type="digit" />

				<!-- <van-field label="下注游戏" :border="false"></van-field> -->
				<div class="px-[12px] !py-[10px] text-[12px]">下注游戏</div>
				<van-field v-for="item in games" :key="item.LotteryId" label-width="80%" :label="item.Name">
					<template #input>
						<div class=" flex-1 row justify-end">
							<van-switch v-model="item.Checked" :active-value="true" :inactive-value="false" active-color="#3976CC"
								inactive-color="#888" @change="handelSwitch(item.Checked!, item.LotteryId)" />
						</div>
					</template>
				</van-field>


			</main>
			<div class="p-[15px] bg-[#FFFFFF]">
				<div class="flex gap-[10px]">
					<van-button @click="confirm" class="!flex-1 !bg-[#3976CC] !text-[#FFFFFF]  rounded-[5px]" block>
						保存
					</van-button>
				</div>
			</div>
		</div>
	</van-popup>
</template>

<script setup lang="ts">
import { cloneDeep, debounce } from "lodash-es";
import { storeToRefs } from "pinia";
import { useGameStore } from "@/store/modules/game";
import { GameCategory } from "@/enums";
import { reqRobotEdit, reqUploadImg, reqRobotAdd } from "@/api/user";
import { toast } from "@/utils/toast";
const baseImgUrl = "https://f.shanshanim.vip"
import { formatCurrency, generateNickname, generateUsername } from "@/utils/common";

const actionChangeIndex = ref(0)
const actionSelect = ref()
const ActionVal = ref(0)
const Actions = [{
	text: '自动上分固定金额',
	value: 1
}, {
	text: '自动上分随机金额',
	value: 2
}];

const uploaderRef = ref()
const onUploaderClick = () => {

}


// 上传图片并发送图片消息
const afterRead: any = async (file: any, obj: any, key: string) => {
	const isIMAGE = file.file.type === "image/jpeg" || "image/jpg" || "image/png";
	// const isLt200K = file.file.size / 1024 < 200;

	if (!isIMAGE) {
		return toast.fail("上传文件只能是图片格式!");
	}
	// if (!isLt200K) {
	// 	return toast.fail("发送图片大小不能超过 200KB!");
	// }
	const loading = toast.loading("上传中...");
	try {
		let param = new FormData();
		param.append("ImgPath", file.file);
		let res = await reqUploadImg(param);
		console.log(res)
		obj[key] = res.data.ImgPath
		obj[key + 's'] = [{ url: obj[key] }]
		console.log(obj);
		file.status = "done";
		loading.close();
	} catch (error) {
		loading.close();
		file.status = "failed";
		console.log(error);
	}
};

interface State {
	updating: boolean;
	isShow: boolean;
}

const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);

const games = computed(() => {
	return gameTotal.value.filter((item: any) => item.CategoryId !== GameCategory.lhc);
})

const props = withDefaults(
	defineProps<{
		data: RobotMo | null;
	}>(),
	{
		data: null
	}
);
const scrollbarRef = ref();
const emit = defineEmits(["update"]);

const state = reactive<State>({
	updating: false,
	isShow: false
});
const defaultForm = {
	Name: "",
	Nickname: "",
	Avatar: "",
	Status: 1,
	DepositType: 1,
	WithdrawType: 1,
	DepositAmount: "200#300#500#800#1000#2000",
	WithdrawAmount: "200#300#500#800#1000#2000",
	MiniBet: "10",
	MaxBet: "200",
	BetGame: ""
};
const form = reactive({ ...defaultForm });
const isEdit = ref(false)

const title = computed(() => {
	return isEdit.value ? '编辑机器人' : '添加机器人'
})

const closed = () => {
	state.isShow = false;
	Object.assign(form, defaultForm);
};

const handleRobotName = () => {
	form.Name = generateUsername()
}

const handleRobotNickname = () => {
  form.Nickname = generateNickname();
};
const open = (edit = false) => {
	isEdit.value = edit
	if(!edit) {
		handleRobotName()
		handleRobotNickname()
	} else {
		initGames();
	}
	state.isShow = true;
};

const initGames = () => {
	if (!props.data) return;
	setTimeout(() => {
		scrollbarRef.value?.setScrollTop(0);
	}, 0);
	Object.assign(form, props.data);
	const betGame: string[] = props.data.BetGame.match(/\d+/g) || [];
	form.BetGame = betGame.length > 0 ? betGame.join(",") : "";
	games.value.forEach((item: any) => {
		item.Checked = betGame.includes(String(item.LotteryId));
	});
};

const handelSwitch = (flag: boolean, id: number) => {
	let betGame = form.BetGame ? form.BetGame.split(",") : [];
	if (flag) {
		betGame.push(String(id));
	} else {
		betGame = betGame.filter(item => Number(item) !== id);
	}
	form.BetGame = betGame.length > 0 ? betGame.join(",") : "";
};

const handleSetAvatar = (img: string) => {
	form.Avatar = img;
};

function validateFormat(input: string) {
	const regex = /^(\d+#)+\d+$/;
	return regex.test(input);
}

const confirm = debounce(
	async () => {
		if (!form.Nickname) {
			return toast.fail("请输入机器人昵称");
		}
		if (form.DepositAmount == "") {
			return toast.fail("请输入自动上分金额");
		}
		if (!validateFormat(form.DepositAmount)) {
			return toast.fail("请输入正确的自动上分金额");
		}
		if (form.WithdrawAmount == "") {
			return toast.fail("请输入自动下分金额");
		}
		if (!validateFormat(form.WithdrawAmount)) {
			return toast.fail("请输入正确的自动下分金额");
		}
		if (form.MiniBet == "") {
			return toast.fail("请输入最小下注金额");
		}
		if (form.MaxBet == "") {
			return toast.fail("请输入最大下注金额");
		}
		if (!form.BetGame) {
			return toast.fail("请选择下注游戏");
		}
		try {
			state.updating = true;
			if(isEdit.value) {
				await reqRobotEdit({
				Id: props.data?.Id,
				...form,
				DepositType: Number(form.DepositType),
				WithdrawType: Number(form.WithdrawType),
				MiniBet: Number(form.MiniBet),
				MaxBet: Number(form.MaxBet),
				BetGame: form.BetGame.split(",")
					.map(num => `{${num}}`)
					.join("")
			});
			toast.success("修改机器人成功");
			} else {
				await reqRobotAdd({
				...form,
				DepositType: Number(form.DepositType),
				WithdrawType: Number(form.WithdrawType),
				MiniBet: Number(form.MiniBet),
				MaxBet: Number(form.MaxBet),
				BetGame: form.BetGame.split(",")
					.map(num => `{${num}}`)
					.join("")
			});
			toast.success("添加机器人成功");
			}
			state.updating = false;
			closed();
			emit("update");
		} catch (error) {
			state.updating = false;
			console.log(error);
		}
	},
	500,
	{ leading: true, trailing: false }
);

// watch(
// 	() => gameTotal.value,
// 	val => {
// 		games.value = cloneDeep(val.filter(item => item.CategoryId !== GameCategory.lhc));
// 	}
// );

watch(
	() => form.DepositType,
	val => {
		if (val == 1) {
			form.DepositAmount = "200#300#500#800#1000#2000";
		} else {
			form.DepositAmount = "200#2000";
		}
	}
);

watch(
	() => form.WithdrawType,
	val => {
		if (val == 1) {
			form.WithdrawAmount = "200#300#500#800#1000#2000";
		} else {
			form.WithdrawAmount = "200#2000";
		}
	}
);

defineExpose({
	open
});
</script>

<style lang="scss" scoped>
.icon {
	width: 14px;
	height: 14px;
	border: none
}
</style>